import path from 'path';
import * as fs from 'fs';
import { parse } from 'csv-parse/sync';

const DATA_DIR = path.join(process.cwd(), 'excel', '06-21');
const UNIT_DEFINITION_FILE = '计量单位定义表.csv';

function debugMeasurementUnits() {
  const filePath = path.join(DATA_DIR, UNIT_DEFINITION_FILE);
  console.log(`读取文件: ${filePath}`);
  
  if (!fs.existsSync(filePath)) {
    console.error(`文件不存在: ${filePath}`);
    return;
  }
  
  let contentBuffer = fs.readFileSync(filePath);
  // Handle BOM
  if (contentBuffer[0] === 0xEF && contentBuffer[1] === 0xBB && contentBuffer[2] === 0xBF) {
    contentBuffer = contentBuffer.subarray(3);
  }
  
  const content = contentBuffer.toString('utf-8');
  console.log('原始内容前5行:');
  const lines = content.split('\n');
  lines.slice(0, 5).forEach((line, index) => {
    console.log(`行 ${index + 1}: ${line}`);
  });
  
  console.log('\n解析后的记录:');
  const records = parse(content, { columns: true, skip_empty_lines: true });
  
  console.log(`总记录数: ${records.length}`);
  console.log('前3条记录:');
  records.slice(0, 3).forEach((record, index) => {
    console.log(`记录 ${index + 1}:`);
    console.log(`  键: ${Object.keys(record).join(', ')}`);
    console.log(`  值: ${JSON.stringify(record)}`);
    
    // 处理每行的多列数据
    const keys = Object.keys(record);
    console.log(`  解析的计量单位对:`);
    for (let i = 0; i < keys.length; i += 2) {
      const categoryKey = keys[i];
      const unitKey = keys[i + 1];
      
      if (categoryKey && unitKey && 
          record[categoryKey] && record[unitKey] &&
          record[categoryKey].trim() !== '' && record[unitKey].trim() !== '' &&
          record[categoryKey] !== '计量类名') {
        
        console.log(`    ${record[categoryKey].trim()} -> ${record[unitKey].trim()}`);
      }
    }
    console.log('');
  });
}

debugMeasurementUnits();
